﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using Terraria;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;

namespace PhantomRealm.Content.Items.Materials
{
    public class AuroraDust : ModItem
    {
        private float auroraTime;
        private readonly List<AuroraPulse> pulses = [];
        private readonly Color AuroraColor1 = new(0, 143, 233);
        private readonly Color AuroraColor2 = new(0, 255, 255);
        private readonly Color AuroraColor3 = new(9, 231, 167);

        public override void SetStaticDefaults()
        {
            Item.ResearchUnlockCount = 100;
        }

        public override void SetDefaults()
        {
            Item.width = 24;
            Item.height = 24;
            Item.maxStack = Item.CommonMaxStack;
            Item.value = Item.sellPrice(0, 0, 10, 0);
            Item.rare = ItemRarityID.White;
        }

        public override void Update(ref float gravity, ref float maxFallSpeed)
        {
            auroraTime += 0.05f;
            if (auroraTime > 1000f)
            {
                auroraTime = 0f;
            }
            if (Main.rand.NextBool(30))
            {
                CreatePulse();
            }
            UpdatePulses();
        }

        private void CreatePulse()
        {
            pulses.Add(new AuroraPulse
            {
                Scale = 1.0f,
                LifeTime = 0,
                MaxLifeTime = 40,
                ColorType = Main.rand.Next(3) 
            });
        }

        private void UpdatePulses()
        {
            for (int i = pulses.Count - 1; i >= 0; i--)
            {
                AuroraPulse pulse = pulses[i];
                pulse.LifeTime++;
                pulse.Scale = 1.0f + (float)pulse.LifeTime / pulse.MaxLifeTime * 0.8f;
                if (pulse.LifeTime >= pulse.MaxLifeTime)
                {
                    pulses.RemoveAt(i);
                }
                else
                {
                    pulses[i] = pulse;
                }
            }
        }

        public override void PostUpdate()
        {
            Lighting.AddLight(Item.Center, new Vector3(0.035f, 0.91f, 0.65f) * 0.4f);
        }

        public override bool PreDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, ref float rotation, ref float scale, int whoAmI)
        {
            Texture2D texture = TextureAssets.Item[Type].Value;
            Vector2 position = Item.position - Main.screenPosition + new Vector2(Item.width * 0.5f, Item.height * 0.5f);
            Vector2 origin = new Vector2(texture.Width * 0.5f, texture.Height * 0.5f);
            foreach (var pulse in pulses)
            {
                float progress = (float)pulse.LifeTime / pulse.MaxLifeTime;
                float alpha = 0.6f * (1f - progress);
                Color pulseColor = pulse.ColorType switch
                {
                    0 => AuroraColor1,
                    1 => AuroraColor2,
                    _ => AuroraColor3  
                };
                pulseColor.A = (byte)(alpha * 255);
                spriteBatch.Draw(texture, position, null, pulseColor,
                    rotation, origin, scale * pulse.Scale, SpriteEffects.None, 0f);
            }
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive,
                Main.DefaultSamplerState, DepthStencilState.None,
                RasterizerState.CullNone, null, Main.GameViewMatrix.TransformationMatrix);
            for (int i = 0; i < 2; i++)
            {
                float timeOffset = auroraTime + i * 0.2f;
                float pulse = (float)System.Math.Sin(timeOffset * 2f) * 0.3f + 0.7f;
                float scaleMultiplier = 1.0f + i * 0.05f;
                float layerAlpha = 0.4f / (i + 1) * pulse;

                Color glowColor = i == 0 ? AuroraColor3 : AuroraColor2;
                glowColor.A = (byte)(layerAlpha * 255);

                spriteBatch.Draw(texture, position, null, glowColor,
                    rotation, origin, scale * scaleMultiplier, SpriteEffects.None, 0f);
            }
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
                Main.DefaultSamplerState, DepthStencilState.None,
                RasterizerState.CullNone, null, Main.GameViewMatrix.TransformationMatrix);
            Color baseColor = Color.Lerp(AuroraColor3, AuroraColor2, (float)System.Math.Sin(auroraTime * 2f) * 0.5f + 0.5f);
            baseColor.A = 200;
            spriteBatch.Draw(texture, position, null, baseColor,
                rotation, origin, scale, SpriteEffects.None, 0f);

            return false;
        }

        public override bool PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin, float scale)
        {
            Texture2D texture = TextureAssets.Item[Type].Value;
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive,
                Main.DefaultSamplerState, DepthStencilState.None,
                RasterizerState.CullNone, null, Main.UIScaleMatrix);
            float pulse = (float)System.Math.Sin(auroraTime * 2f) * 0.2f + 0.8f;
            Color glowColor = AuroraColor2;
            glowColor.A = (byte)(100 * pulse);

            spriteBatch.Draw(texture, position, frame, glowColor,
                0f, origin, scale * 1.1f, SpriteEffects.None, 0f);
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
                Main.DefaultSamplerState, DepthStencilState.None,
                RasterizerState.CullNone, null, Main.UIScaleMatrix);
            Color baseColor = Color.Lerp(AuroraColor3, AuroraColor2, (float)System.Math.Sin(auroraTime * 2f) * 0.5f + 0.5f);
            spriteBatch.Draw(texture, position, frame, baseColor,
                0f, origin, scale, SpriteEffects.None, 0f);
            return false;
        }
        private struct AuroraPulse
        {
            public float Scale;
            public int LifeTime;
            public int MaxLifeTime;
            public int ColorType; 
        }
    }
}